'''
Author        zzx
Date          2022-08-08 09:26:32
LastEditTime  2022-10-24 13:59:01
LastEditors   zzx
Description   字典模型
'''


from sqlalchemy import UniqueConstraint
from app.extensions.sqlalchemy import db, EntityModel as Base
from app.extensions.initialization.dict_data import base_data
from app.modules.v1.permission.models import roles_dicts


class DictType(Base):
    '''字典类型'''
    __tablename__ = 'dict_type'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    value = db.Column(db.String(64), unique=True, comment='字典类型键')
    label = db.Column(db.String(64), nullable=False, comment='字典名称')
    parent_id = db.Column(db.Integer, comment='父级节点')
    status = db.Column(db.Boolean, default=True, comment='状态(True正常, False停用)')
    remark = db.Column(db.Text, comment='备注')
    dicts = db.relationship('Dict', backref='dict-type', lazy='dynamic',
                            cascade='all, delete-orphan', passive_deletes=True)


class Dict(Base):
    '''字典数据'''
    __tablename__ = 'dict'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    value = db.Column(db.String(64), index=True, comment='字典键值')
    label = db.Column(db.String(64), nullable=False, comment='字典标签')
    parent_id = db.Column(db.Integer, comment='父级节点')
    type_id = db.Column(db.Integer, db.ForeignKey("dict_type.id", ondelete='CASCADE'), index=True, comment='字典类型')
    css_class = db.Column(db.String(64), comment='样式属性（其他样式扩展）')
    list_class = db.Column(
        db.String(64), comment='表格回显样式(默认default, 主要primary, 成功success, 信息info, 警告warning, 危险danger)')
    is_default = db.Column(db.Boolean, default=False, comment='是否默认(True是, False否)')
    order = db.Column(db.Integer, nullable=False, default=0, comment='字典排序')
    status = db.Column(db.Boolean, default=True, comment='状态(True正常, False停用)')
    remark = db.Column(db.Text, comment='备注')
    nums = db.Column(db.Integer, comment='数据值')
    level = db.Column(db.Integer, default=1, comment='等级')
    roles = db.relationship('Role', secondary=roles_dicts, back_populates='dicts', lazy='dynamic')

    __table_args__ = (
        UniqueConstraint('type_id', 'value', name='uix_type_value'),  # 联合唯一索引
    )

    def get_children(self):
        children = Dict.get_all(parent_id=self.id)
        return children

    @property
    def parent(self):
        parent = Dict.get(id=self.parent_id)
        return parent

    @staticmethod
    def init_data():

        def multi_children(children, dict_type_id, parent_id=None):
            for child in children:
                print(child)
                _dict_data = Dict.get(value=child['value'], type_id=dict_type_id)
                if not _dict_data:
                    _dict_data = Dict.create(**child, type_id=dict_type_id, parent_id=parent_id)
                else:
                    _dict_data.update(**child, parent_id=parent_id)

                _children = child.get('children', [])
                print('child_children', _children)
                print('\n')
                if _children:
                    multi_children(_children, dict_type_id, _dict_data.id)

        for item in base_data:
            _dict_type = DictType.get(value=item['value'])
            if not _dict_type:
                _dict_type = DictType.create(value=item['value'], label=item['label'])
            else:
                _dict_type.update(**item)
            if item['value'] == 'import_dicts':
                children = item.get('children', [])
                # print(children)
                if children:
                    multi_children(children, _dict_type.id, parent_id=None)
            # for _dict in item['children']:
            #     _dict_data = Dict.get(value=_dict['value'], type_id=_dict_type.id)
            #     if not _dict_data:
            #         _dict_data = Dict.create(**_dict, type_id=_dict_type.id)
            #     else:
            #         _dict_data.update(**_dict)
